package com.hurui.xiaoming.utils;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

/**
 * Created by Administrator on 2017/7/27.
 */

public class ImageOnkitKat  {
    private final int REQUSET_CODE=10010;
    /**
     *
     * @param context
     * @param
     * @return
     */
    @TargetApi(19)
    public static  String handleImageBeforeKitKat(Context context, Intent data){
        String imagePath=null;
        Uri uri=data.getData();
        if(Build.VERSION.SDK_INT>=19){
            if(DocumentsContract.isDocumentUri(context,uri)){
                String docId=DocumentsContract.getDocumentId(uri);
                if("com.android.providers.media.documents".equals(uri.getAuthority())){
                    String id=docId.split(":")[1];
                    String selection= MediaStore.Images.Media._ID+"="+id;

                    imagePath=getImagePath(context,MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);

                }else if("com.android.provider.downloads.documents".equals(uri.getAuthority())){
                    Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                    imagePath=getImagePath(context,contentUri,null);
                }
            }else if("content".equalsIgnoreCase(uri.getScheme())){
                imagePath=getImagePath(context,uri,null);
            }else if("file".equalsIgnoreCase(uri.getScheme())){
                imagePath=uri.getPath();
            }
        }else
            imagePath=getImagePath(context,uri,null);

        return imagePath;
    }
    /**
     * 获取图片路径
     * @param uri
     * @param selection
     * @return
     */
    private static   String getImagePath(Context context,Uri uri,String selection){
        String path=null;
        Cursor cursor=context.getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


}
